package lion.formail.reader.accountcfg;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class AccountcfgReader {

	private int boxCount;

	private List<MailBox> mailBoxList = new ArrayList<MailBox>();

	public int getBoxCount() {

		return boxCount;
	}

	public void setBoxCount(int boxCount) {

		this.boxCount = boxCount;
	}

	public List<MailBox> getMailBoxList() {

		return mailBoxList;
	}

	public void setMailBoxTree(List<MailBox> mailBoxList) {

		this.mailBoxList = mailBoxList;
	}

	public void read(File accountCfg) throws IOException {

		byte[] boxBuf = new byte[0x04];

		try {

			ComReader comreader = new ComReader();

			boxBuf = comreader.getBoxByteArray(accountCfg);

			// boxCount

			boxCount = ComReader.getReverseBytesInt(boxBuf, 256);

			byte[] mailBoxContentBuf = new byte[0x106];

			// read boxCount
			for (int i = 0; i < boxCount; i++) {

				ComReader.copyByteArray(mailBoxContentBuf, boxBuf, 260 + i * 262, 262);
				MailBox mailbox = new MailBox();

				// get level
				mailbox.setLevel(ComReader.getReverseBytesInt(mailBoxContentBuf, 0));

				// ID
				mailbox.setId(new Integer(mailBoxContentBuf[0x05]));

				// BoxName
				int j = 0;
				while (mailBoxContentBuf[0x9 + j] != 0) {
					j++;
				}
				mailbox.setBoxName(new String(mailBoxContentBuf, 0x09, j));

				// LogicName
				j = 0;
				while (mailBoxContentBuf[j + 0x49] != 0) {
					j++;
				}
				mailbox.setLogicName(new String(mailBoxContentBuf, 0x49, j));
				mailBoxList.add(mailbox);
			}
		} catch (IOException ex) {
			ex.printStackTrace();
			throw new IOException("解析邮箱信息失败");
		}

	}

	public MailBox getMailBoxByPath(MailBox node, String[] paths) {

		List<MailBox> subNodes = node.getSubMailBox();

		for (int i = 0; i < subNodes.size(); i++) {
			MailBox box = subNodes.get(i);
			if (box.getBoxName().equals(paths)) { return box; }
		}
		return null;
	}

}
